<template>
  <div class="article-interaction-container">
    <!-- 1. 顶部统计卡片 -->
    <el-row :gutter="20" class="mb-20px">
      <el-col :span="6" v-for="(item, index) in statisticsData" :key="index">
        <div :class="['statistics-card', `gradient-${index + 1}`]" v-loading="loading">
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon>
                <component :is="item.icon" />
                <div class="icon-effect"></div>
              </el-icon>
            </div>
            <div class="data-wrapper">
              <count-to
                :start-val="0"
                :end-val="item.value"
                :duration="2000"
                :separator="','"
                class="card-value"
              />
              <div class="card-title">{{ item.title }}</div>
            </div>
          </div>
          <div class="trend-indicator">
            <span :class="['trend-value', item.trend]">
              {{ item.growthRate }}%
              <el-icon>
                <component :is="item.trend === 'up' ? ArrowUpBold : ArrowDownBold" />
              </el-icon>
            </span>
            <span class="trend-label">较上周期</span>
          </div>
          <div class="card-effect"></div>
        </div>
      </el-col>
    </el-row>

    <!-- 2. 主要图表区域 - 调整为两行两列布局 -->
    <el-row :gutter="20" class="mb-20px">
      <!-- 2.1 趋势图 -->
      <el-col :span="24" class="mb-20px">
        <div class="chart-card">
          <div class="chart-header">
            <div class="header-left">
              <h3>文章交互趋势分析</h3>
              <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">全年</el-radio-button>
              </el-radio-group>
            </div>
            <div class="header-right">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="default"
                :shortcuts="dateShortcuts"
                @change="handleDateChange"
              />
            </div>
          </div>
          <div class="chart-container">
            <Echart :options="trendChartOption" :height="400" />
          </div>
        </div>
      </el-col>

      <!-- 2.2 交互类型对比 -->
      <el-col :span="8">
        <div class="chart-card">
          <div class="chart-header">
            <h3>交互类型对比</h3>
            <el-radio-group v-model="interactionTimeRange" size="small">
              <el-radio-button label="day">今日</el-radio-button>
              <el-radio-button label="week">本周</el-radio-button>
              <el-radio-button label="month">本月</el-radio-button>
            </el-radio-group>
          </div>
          <div class="chart-container">
            <Echart :options="barChartOption" :height="300" />
          </div>
        </div>
      </el-col>

      <!-- 2.3 分类数据统计 -->
      <el-col :span="8">
        <div class="chart-card">
          <div class="chart-header">
            <h3>分类交互占比</h3>
            <el-switch
              v-model="categoryChart3D"
              active-text="3D"
              inactive-text="2D"
              @change="toggleCategoryChart3D"
            />
          </div>
          <div class="chart-container">
            <Echart ref="categoryChartRef" :options="categoryChartOption" :height="300" />
          </div>
        </div>
      </el-col>

      <!-- 2.4 浏览器分布 -->
      <el-col :span="8">
        <div class="chart-card">
          <div class="chart-header">
            <h3>浏览器分布</h3>
            <el-tooltip content="点击查看详细数据" placement="top">
              <el-button type="primary" link @click="showBrowserDetail">
                <el-icon><InfoFilled /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
          <div class="chart-container">
            <Echart :options="browserChartOption" :height="300" />
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 3. 数据表格区域 -->
    <div class="data-table-card">
      <div class="table-header">
        <div class="header-title">
          <el-icon class="header-icon"><DataAnalysis /></el-icon>
          <span>交互详细数据</span>
        </div>
        <div class="header-actions">
          <el-tooltip content="刷新数据" placement="top">
            <el-button :icon="Refresh" circle @click="refreshList" />
          </el-tooltip>
          <el-button type="primary" @click="exportData">
            <el-icon><Download /></el-icon>导出数据
          </el-button>
        </div>
      </div>

      <div class="filter-container">
        <el-form :inline="true" :model="queryParams" class="search-form">
          <el-form-item label="文章标题">
            <el-input
              v-model="queryParams.keyword"
              placeholder="请输入文章标题"
              clearable
              :prefix-icon="Search"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="交互类型">
            <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.MZT_ARTICLE_INTERACTION_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="文章分类">
            <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
              <el-option
                v-for="category in categoryOptions"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="queryParams.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :shortcuts="dateShortcuts"
            />
          </el-form-item>
          <el-form-item class="search-buttons">
            <el-button type="primary" :icon="Search" @click="handleQuery">查询</el-button>
            <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        v-loading="loading"
        :data="list"
        :stripe="true"
        :border="true"
        :highlight-current-row="true"
        class="modern-table"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="文章" align="left" prop="articleTitle" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="article-cell">
              <el-link type="primary" class="article-link" @click="handleArticleClick(row)">
                {{ row.articleTitle }}
              </el-link>
              <el-tag size="small" effect="plain" class="article-tag">
                {{ row.categoryName }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" prop="type" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.type === 'VIEW' ? 'success' : 'warning'"
              effect="light"
              size="small"
              class="status-tag"
            >
              <el-icon class="tag-icon">
                <View v-if="row.type === 'VIEW'" />
                <Star v-else />
              </el-icon>
              {{ row.type === 'VIEW' ? '浏览' : '点赞' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="IP地址" align="center" prop="ip" width="160">
          <template #default="{ row }">
            <div class="ip-cell">
              <span class="ip-address">{{ row.ip }}</span>
              <el-tooltip :content="row.location || '未知位置'" placement="top">
                <el-icon class="location-icon"><Location /></el-icon>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="设备信息" align="center" prop="userAgent" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="device-cell">
              <el-icon class="device-icon">
                <Monitor v-if="row.deviceType === 'desktop'" />
                <Document v-else-if="row.deviceType === 'mobile'" />
                <Document v-else />
              </el-icon>
              <span>{{ row.userAgent }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="180"
          sortable
        >
          <template #default="{ row }">
            <div class="time-cell">
              <span class="create-time">{{ dateFormatter(row.createTime, 'YYYY-MM-DD') }}</span>
              <span class="create-time-detail">{{ dateFormatter(row.createTime, 'HH:mm:ss') }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加浏览器详情弹窗 -->
    <el-dialog
      v-model="browserDetailVisible"
      title="浏览器访问详情"
      width="800px"
      :destroy-on-close="true"
    >
      <el-table
        :data="browserDetailData"
        :stripe="true"
        :border="true"
        height="400"
        class="browser-detail-table"
      >
        <el-table-column prop="browser" label="浏览器" align="center" />
        <el-table-column prop="version" label="版本" align="center" />
        <el-table-column prop="visits" label="访问次数" align="center" />
        <el-table-column prop="percentage" label="占比" align="center">
          <template #default="{ row }">
            <div class="percentage-wrapper">
              <el-progress
                :percentage="row.percentage"
                :color="row.color"
                :stroke-width="16"
                :format="(val) => val + '%'"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="trend" label="趋势" align="center" width="180">
          <template #default="{ row }">
            <div class="trend-wrapper">
              <span :class="['trend-value', row.trend]">
                {{ row.trendValue }}%
                <el-icon>
                  <component :is="row.trend === 'up' ? ArrowUpBold : ArrowDownBold" />
                </el-icon>
              </span>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="browser-stats mt-20px">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stats-card">
              <div class="stats-title">移动端占比</div>
              <div class="stats-value">{{ mobilePercentage }}%</div>
              <div class="stats-trend" :class="mobileTrend">
                较上周期 {{ mobileTrendValue }}%
                <el-icon>
                  <component :is="mobileTrend === 'up' ? ArrowUpBold : ArrowDownBold" />
                </el-icon>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stats-card">
              <div class="stats-title">桌面端占比</div>
              <div class="stats-value">{{ desktopPercentage }}%</div>
              <div class="stats-trend" :class="desktopTrend">
                较上周期 {{ desktopTrendValue }}%
                <el-icon>
                  <component :is="desktopTrend === 'up' ? ArrowUpBold : ArrowDownBold" />
                </el-icon>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stats-card">
              <div class="stats-title">平均停留时间</div>
              <div class="stats-value">{{ avgStayTime }}分钟</div>
              <div class="stats-trend" :class="stayTimeTrend">
                较上周期 {{ stayTimeTrendValue }}%
                <el-icon>
                  <component :is="stayTimeTrend === 'up' ? ArrowUpBold : ArrowDownBold" />
                </el-icon>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { ArticleInteractionApi, ArticleInteractionVO } from '@/api/mzt/articleinteraction'
import { EChartsOption } from 'echarts'
import { CountTo } from '@/components/CountTo'
import {
  View,
  Star,
  Document,
  FolderOpened,
  ArrowUpBold,
  ArrowDownBold,
  Search,
  Refresh,
  InfoFilled,
  DataAnalysis,
  Download,
  Location,
  Monitor
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {CategoryApi} from "@/api/mzt/category";
import {TagApi} from "@/api/mzt/tag";

defineOptions({ name: 'ArticleInteraction' })

const loading = ref(true)
const list = ref<ArticleInteractionVO[]>([])
const total = ref(0)
const dateRange = ref([])
const categoryOptions = ref([])

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  type: undefined,
  categoryId: undefined,
  dateRange: []
})

// 顶部统计数据
const statisticsData = ref([
  { title: '总浏览量', value: 0, icon: View, trend: 'up' },
  { title: '总点赞数', value: 0, icon: Star, trend: 'up' },
  { title: '文章数量', value: 0, icon: Document, trend: 'flat' },
  { title: '分类数量', value: 0, icon: FolderOpened, trend: 'up' }
])

// 图表3D切换
const categoryChart3D = ref(false)
const timeRange = ref('week')

// 添加 ref 用于获取图表实例
const categoryChartRef = ref()

// 2D配置
const pie2DOption = {
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  backgroundColor: '#ffffff',
  legend: {
    orient: 'vertical',
    left: 'left',
    textStyle: {
      color: '#333'
    }
  },
  series: [{
    name: '分类交互',
    type: 'pie',
    radius: ['40%', '70%'],
    center: ['50%', '50%'],
    roseType: false,
    itemStyle: {
      borderRadius: 8,
      borderColor: '#fff',
      borderWidth: 2
    },
    label: {
      show: true,
      formatter: '{b}: {c} ({d}%)',
      color: '#333'
    },
    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    },
    data: []
  }]
}

// 3D配置
const pie3DOption = {
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  backgroundColor: '#2c343c',
  legend: {
    orient: 'vertical',
    left: 'left',
    textStyle: {
      color: '#fff'
    }
  },
  series: [{
    name: '分类交互',
    type: 'pie',
    radius: ['30%', '60%'],
    center: ['50%', '50%'],
    roseType: 'area',
    itemStyle: {
      borderRadius: 8,
      borderColor: '#fff',
      borderWidth: 3,
      opacity: 0.7,
      shadowBlur: 10,
      shadowColor: 'rgba(0, 0, 0, 0.2)'
    },
    label: {
      show: true,
      formatter: '{b}: {c} ({d}%)',
      color: '#fff'
    },
    emphasis: {
      itemStyle: {
        shadowBlur: 20,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      },
      label: {
        show: true,
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    data: []
  }]
}

// 初始化分类图表配置
const categoryChartOption = ref(pie2DOption)

// 趋势图配置
const trendChartOption = ref<EChartsOption>({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['浏览量', '点赞数']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '浏览量',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#1890ff'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(24,144,255,0.3)' },
          { offset: 1, color: 'rgba(24,144,255,0.1)' }
        ])
      }
    },
    {
      name: '点赞数',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#ff4d4f'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(255,77,79,0.3)' },
          { offset: 1, color: 'rgba(255,77,79,0.1)' }
        ])
      }
    }
  ]
})

// 浏览器分布图配置
const browserChartOption = ref<EChartsOption>({
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    right: 10,
    top: 'center'
  },
  series: [
    {
      name: '浏览器分布',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 1048, name: 'Chrome', itemStyle: { color: '#1890ff' } },
        { value: 735, name: 'Firefox', itemStyle: { color: '#ff4d4f' } },
        { value: 580, name: 'Safari', itemStyle: { color: '#52c41a' } },
        { value: 484, name: 'Edge', itemStyle: { color: '#faad14' } },
        { value: 300, name: 'Others', itemStyle: { color: '#722ed1' } }
      ]
    }
  ]
})


// 交互类型对比图配置
const barChartOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    data: ['浏览量', '点赞量']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['技术文章', '生活随笔', '产品设计', '开发教程', '其他分类']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '浏览量',
      type: 'bar',
      data: [320, 302, 301, 334, 290]
    },
    {
      name: '点赞量',
      type: 'bar',
      data: [120, 132, 101, 134, 90]
    }
  ]
})



// 浏览器详情相关的状态
const browserDetailVisible = ref(false)
const browserDetailData = ref([])
const mobilePercentage = ref(35.8)
const desktopPercentage = ref(64.2)
const avgStayTime = ref(4.5)
const mobileTrend = ref('up')
const desktopTrend = ref('down')
const stayTimeTrend = ref('up')
const mobileTrendValue = ref(2.5)
const desktopTrendValue = ref(-1.8)
const stayTimeTrendValue = ref(0.5)

// 获取统计数据
const getStatisticsData = async () => {
  try {
    loading.value = true
    // 模拟数据
    const mockData = {
      viewCount: 12580,
      likeCount: 3456,
      articleCount: 126,
      categoryCount: 8,
      viewGrowth: 12.5,
      likeGrowth: 8.3,
      articleGrowth: 0,
      categoryGrowth: 25
    }

    statisticsData.value = [
      {
        title: '总浏览量',
        value: mockData.viewCount,
        icon: View,
        trend: 'up',
        growthRate: mockData.viewGrowth
      },
      {
        title: '总点赞数',
        value: mockData.likeCount,
        icon: Star,
        trend: 'up',
        growthRate: mockData.likeGrowth
      },
      {
        title: '文章数量',
        value: mockData.articleCount,
        icon: Document,
        trend: 'flat',
        growthRate: mockData.articleGrowth
      },
      {
        title: '分类数量',
        value: mockData.categoryCount,
        icon: FolderOpened,
        trend: 'up',
        growthRate: mockData.categoryGrowth
      }
    ]
  } catch (error) {
    console.error('获取统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取趋势数据
const getTrendData = async () => {
  try {
    // 模拟数据
    const mockData = {
      dates: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      viewCounts: [820, 932, 901, 934, 1290, 1330, 1320],
      likeCounts: [320, 332, 301, 334, 390, 330, 320]
    }

    // 更新图表数据
    trendChartOption.value.xAxis.data = mockData.dates
    trendChartOption.value.series[0].data = mockData.viewCounts
    trendChartOption.value.series[1].data = mockData.likeCounts
  } catch (error) {
    console.error('获取趋势数据失败:', error)
  }
}

// 获取分类数据
const getCategoryData = async () => {
  try {
    // 模拟数据
    const mockData = [
      { value: 1048, name: '技术文章' },
      { value: 735, name: '生活随笔' },
      { value: 580, name: '产品设计' },
      { value: 484, name: '开发教程' },
      { value: 300, name: '其他分类' }
    ]

    categoryChartOption.value = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '访问来源',
          type: 'pie',
          radius: '50%',
          data: mockData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
  } catch (error) {
    console.error('获取分类数据失败:', error)
  }
}

// 获取浏览器分布数据
const getBrowserData = async () => {
  try {
    // 模拟数据
    const mockData = [
      { value: 1048, name: 'Chrome', itemStyle: { color: '#1890ff' } },
      { value: 735, name: 'Firefox', itemStyle: { color: '#ff4d4f' } },
      { value: 580, name: 'Safari', itemStyle: { color: '#52c41a' } },
      { value: 484, name: 'Edge', itemStyle: { color: '#faad14' } },
      { value: 300, name: 'Others', itemStyle: { color: '#722ed1' } }
    ]

    // 更新图表数据
    browserChartOption.value.series[0].data = mockData
  } catch (error) {
    console.error('获取浏览器分布数据失败:', error)
  }
}

// 查询列表数据
const getList = async () => {
  loading.value = true
  try {
    // 模拟数据
    const mockData = {
      list: Array.from({ length: 10 }, (_, index) => ({
        id: index + 1,
        articleTitle: `示例文章标题 ${index + 1}`,
        categoryName: ['技术文章', '生活随笔', '产品设计', '开发教程'][index % 4],
        type: index % 2 === 0 ? 'VIEW' : 'LIKE',
        ip: `192.168.1.${index + 1}`,
        createTime: '2024-01-10 12:00:00'
      })),
      total: 100
    }

    list.value = mockData.list
    total.value = mockData.total
  } finally {
    loading.value = false
  }
}

// 日期变化处理
const handleDateChange = () => {
  getTrendData()
}

// 查询按钮操作
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.type = undefined
  queryParams.categoryId = undefined
  handleQuery()
}

// 切换图表3D效果
const toggleCategoryChart3D = (enabled: boolean) => {
  // 保存当前数据
  const currentData = categoryChartOption.value.series[0].data

  // 准备新的配置
  const newOption = enabled ? pie3DOption : pie2DOption
  newOption.series[0].data = currentData

  // 更新配置
  categoryChartOption.value = newOption

  // 强制重新渲染图表
  nextTick(() => {
    const chart = categoryChartRef.value?.getChart()
    if (chart) {
      chart.setOption(newOption, true)
    }
  })
}

// 时间范围变化处理
const handleTimeRangeChange = (value: string) => {
  getTrendData() // 重新获取趋势数据
}

// 添加日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 显示浏览器详情
const showBrowserDetail = async () => {
  try {
    loading.value = true
    // 模拟获取详细数据
    browserDetailData.value = [
      {
        browser: 'Chrome',
        version: '120.0',
        visits: 15680,
        percentage: 45.8,
        trend: 'up',
        trendValue: 2.3,
        color: '#1890ff'
      },
      {
        browser: 'Firefox',
        version: '121.0',
        visits: 8920,
        percentage: 26.1,
        trend: 'down',
        trendValue: -1.5,
        color: '#ff4d4f'
      },
      {
        browser: 'Safari',
        version: '17.0',
        visits: 5340,
        percentage: 15.6,
        trend: 'up',
        trendValue: 0.8,
        color: '#52c41a'
      },
      {
        browser: 'Edge',
        version: '120.0',
        visits: 3280,
        percentage: 9.6,
        trend: 'up',
        trendValue: 1.2,
        color: '#faad14'
      },
      {
        browser: 'Others',
        version: '-',
        visits: 980,
        percentage: 2.9,
        trend: 'down',
        trendValue: -0.5,
        color: '#722ed1'
      }
    ]
    browserDetailVisible.value = true
  } catch (error) {
    console.error('获取浏览器详细数据失败:', error)
    ElMessage.error('获取详细数据失败')
  } finally {
    loading.value = false
  }
}
const init = async () => {
  const category = await CategoryApi.getCategoryStatus({type:"TOP"})
  categoryOptions.value =category;
}
// 在 onMounted 中确保调用数据获取函数
onMounted(async () => {
  try {
    loading.value = true
    await Promise.all([
      init(),
      getStatisticsData(),
      getTrendData(), // 确保调用趋势数据
      getCategoryData(),
      getBrowserData(), // 确保调用浏览器数据
      getList()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
  } finally {
    loading.value = false
  }
})

// 添加导出数据功能
const exportData = () => {
  ElMessageBox.confirm('确认导出交互数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实现导出逻辑
    ElMessage.success('导出成功')
  })
}

// 添加刷新列表功能
const refreshList = async () => {
  await getList()
  ElMessage.success('数据已刷新')
}
</script>

<style lang="scss" scoped>
.article-interaction-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;

  .statistics-card {
    padding: 24px;
    border-radius: 12px;
    transition: all 0.3s;
    position: relative;
    overflow: hidden;
    cursor: pointer;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    }

    .card-content {
      display: flex;
      align-items: center;
      gap: 16px;
    }

    .icon-wrapper {
      width: 48px;
      height: 48px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(255, 255, 255, 0.2);

      .el-icon {
        font-size: 24px;
        color: #fff;
      }
    }

    .data-wrapper {
      flex: 1;
    }

    .card-value {
      font-size: 28px;
      font-weight: bold;
      color: #fff;
      line-height: 1.2;
      margin-bottom: 4px;
    }

    .card-title {
      font-size: 14px;
      color: rgba(255, 255, 255, 0.85);
    }

    .trend-indicator {
      margin-top: 16px;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .trend-value {
      display: flex;
      align-items: center;
      gap: 4px;
      font-weight: 500;

      &.up {
        color: #52c41a;
      }

      &.down {
        color: #ff4d4f;
      }
    }

    .trend-label {
      font-size: 12px;
      color: rgba(255, 255, 255, 0.65);
    }

    // 添加图标特效
    .icon-wrapper {
      position: relative;

      .icon-effect {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
        height: 100%;
        border-radius: 12px;
        background: rgba(255, 255, 255, 0.1);
        opacity: 0;
        transition: all 0.3s;
      }

      &:hover {
        .icon-effect {
          opacity: 1;
          animation: pulse 1.5s infinite;
        }

        .el-icon {
          animation: bounce 0.5s;
        }
      }
    }

    // 添加卡片光效
    .card-effect {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(
          225deg,
          transparent 0%,
          rgba(255, 255, 255, 0.1) 50%,
          transparent 100%
      );
      transform: translateX(-100%);
      transition: transform 0.5s;
    }

    &:hover {
      .card-effect {
        transform: translateX(100%);
      }

      .trend-value {
        &.up {
          animation: slideUp 0.3s ease-out;
        }
        &.down {
          animation: slideDown 0.3s ease-out;
        }
      }
    }
  }

  // 渐变背景
  .gradient-1 {
    background: linear-gradient(135deg, #1890ff, #36cfc9);
  }

  .gradient-2 {
    background: linear-gradient(135deg, #722ed1, #eb2f96);
  }

  .gradient-3 {
    background: linear-gradient(135deg, #52c41a, #13c2c2);
  }

  .gradient-4 {
    background: linear-gradient(135deg, #faad14, #fa541c);
  }

  .chart-card {
    background: #fff;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    height: 100%; // 确保同一行的卡片高度一致

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;

      h3 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #1f2937;
      }
    }

    .chart-container {
      height: calc(100% - 60px); // 减去头部高度
    }
  }

  .data-table-card {
    background: #fff;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      padding-bottom: 16px;
      border-bottom: 1px solid #f0f0f0;

      .header-title {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 20px;
        font-weight: 600;
        color: #1f2937;

        .header-icon {
          font-size: 24px;
          color: #4b5563;
        }
      }
    }

    .filter-container {
      margin: -8px -16px 24px;
      padding: 20px;
      background-color: #f9fafb;
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        background-color: #f3f4f6;
      }

      .search-form {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;

        .el-form-item {
          margin-bottom: 0;

          &__label {
            font-weight: 500;
            color: #4b5563;
          }
        }

        .el-input,
        .el-select {
          width: 240px;

          :deep(.el-input__wrapper) {
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
          }
        }

        .search-buttons {
          margin-left: auto;

          .el-button {
            padding: 8px 16px;
            transition: all 0.3s ease;

            &:hover {
              transform: translateY(-1px);
            }
          }
        }
      }
    }

    .modern-table {
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #e5e7eb;

      :deep(.el-table__header) {
        th {
          background-color: #f9fafb;
          color: #374151;
          font-weight: 600;
          padding: 12px 0;
          border-bottom: 2px solid #e5e7eb;
        }
      }

      :deep(.el-table__row) {
        td {
          padding: 16px 0;
          transition: all 0.3s ease;
        }

        &:hover td {
          background-color: #f9fafb;
        }
      }

      .article-cell {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 0 8px;

        .article-link {
          flex: 1;
          font-weight: 500;

          &:hover {
            color: #1d4ed8;
            text-decoration: underline;
          }
        }

        .article-tag {
          flex-shrink: 0;
        }
      }

      .ip-cell {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;

        .ip-address {
          font-family: 'Roboto Mono', monospace;
          color: #6b7280;
        }

        .location-icon {
          color: #9ca3af;
          cursor: pointer;
          transition: color 0.3s;

          &:hover {
            color: #6b7280;
          }
        }
      }

      .device-cell {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;

        .device-icon {
          color: #9ca3af;
        }
      }

      .time-cell {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 2px;

        .create-time {
          color: #374151;
          font-weight: 500;
        }

        .create-time-detail {
          color: #9ca3af;
          font-size: 12px;
        }
      }
    }

    .pagination-container {
      margin-top: 24px;
      padding-top: 16px;
      border-top: 1px solid #f0f0f0;
      display: flex;
      justify-content: flex-end;

      :deep(.el-pagination) {
        button {
          border-radius: 4px;
        }

        .el-pagination__sizes {
          margin-right: 16px;
        }
      }
    }
  }
}

// 添加一些动画效果
.modern-table {
  :deep(.el-table__row) {
    transition: transform 0.3s ease;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    }
  }
}

// 添加动画关键帧
@keyframes pulse {
  0% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 0.5;
  }
  50% {
    transform: translate(-50%, -50%) scale(1.2);
    opacity: 0.2;
  }
  100% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 0.5;
  }
}

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}

@keyframes slideUp {
  0% {
    transform: translateY(5px);
    opacity: 0.5;
  }
  100% {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes slideDown {
  0% {
    transform: translateY(-5px);
    opacity: 0.5;
  }
  100% {
    transform: translateY(0);
    opacity: 1;
  }
}

.browser-detail-table {
  .percentage-wrapper {
    padding: 0 20px;
  }

  .trend-wrapper {
    .trend-value {
      display: inline-flex;
      align-items: center;
      gap: 4px;

      &.up {
        color: #52c41a;
      }

      &.down {
        color: #ff4d4f;
      }
    }
  }
}

.browser-stats {
  .stats-card {
    background: #f9fafb;
    border-radius: 8px;
    padding: 16px;
    text-align: center;

    .stats-title {
      color: #6b7280;
      font-size: 14px;
      margin-bottom: 8px;
    }

    .stats-value {
      font-size: 24px;
      font-weight: 600;
      color: #1f2937;
      margin-bottom: 8px;
    }

    .stats-trend {
      font-size: 13px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;

      &.up {
        color: #52c41a;
      }

      &.down {
        color: #ff4d4f;
      }
    }
  }
}
</style>
